<template>
  <div class="comprehensive-form-container">
    <el-form
      ref="formRef"
      v-loading="data.loading"
      :disabled="data.disabled"
      label-width="100px"
      :model="data.form"
      :rules="rules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="data.form.username" disabled readonly />
      </el-form-item>
      <el-form-item label="角色">
        <el-tag
          v-for="item in data.form.roles"
          :key="item"
          effect="dark"
          :type="'success'"
        >
          {{ item }}
        </el-tag>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="data.form.name" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="data.form.phone" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="data.form.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="data.form.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('formRef')">
          保存
        </el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import request from '@/utils/request'
  import { gp } from '@gp'
  const data = reactive({
    form: {},
    userInfo: {},
    loading: false,
  })
  const formRef = ref(null)

  const rules = reactive({
    name: { required: true, message: '姓名必须填写' },
    phone: { required: true, message: '手机号必须填写' },
    email: { required: true, type: 'email', message: '电子邮箱必须填写' },
  })

  onMounted(async () => {
    const { data: d } = await request({
      url: '/uc/user_info',
    })
    data.userInfo = Object.assign({}, d)
    data.form = d
  })

  const resetForm = () => {
    data.form = Object.assign({}, data.userInfo)
  }

  const submitForm = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        data.disabled = true
        data.loading = true

        // 发送更新 http请求
        const { code } = await request({
          url: '/uc/update_user',
          method: 'post',
          data: data.form,
        }).finally(() => {
          data.disabled = false
          data.loading = false
        })
        if (code == 200) {
          gp.$baseMessage('修改成功', 'success', 'vab-hey-message-success')
        }
      }
    })
  }
</script>
